package com.example.demo.shiro;

import com.example.demo.entity.SysPermission;
import com.example.demo.entity.SysRole;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by hly on 2018\11\14 0014.
 * shiro中用户自定义登录验证和授权认证的地方（realm）
 */
public class EnceladusShiroRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    /**
     * 授权认证
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //负责装载role和permission的对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取用户名
        String username = (String) principal.getPrimaryPrincipal();
        //获取用户
        User user = userService.findUserByName(username);
        //遍历角色和权限，并把名称加入到authorizationInfo中
        for (SysRole role:user.getRoles()) {
            authorizationInfo.addRole(role.getRole());
            for(SysPermission permission:role.getPermissions()) {
                authorizationInfo.addStringPermission(permission.getName());
            }
        }
        return authorizationInfo;
    }

    /**
     * 登录验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String)token.getPrincipal();
        //查寻用户
        User user = userService.findUserByName(username);
        //逻辑
        if (user == null) {
            return null;
        }
        //包装对象（用户名、密码、用户Salt、抽象类CachingRealm的getName()）
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),getName());
        System.out.println("getName():"+getName());
        //返回SimpleAuthenticationInfo对象
        return authenticationInfo;
    }
}
